package org.teremail.mailbox;

import static org.teremail.mailbox.Path.path;

import java.util.List;

import org.teremail.message.Message;

public class MailboxProxy implements Mailbox {

    private final MailboxDO mailbox;
    private final MailboxServiceImpl service;
    private final Path INBOX = path("INBOX");

    public MailboxProxy(MailboxServiceImpl service, MailboxDO mailbox) {
        this.service = service;
        this.mailbox = mailbox;
    }

    public Folder getFolder(Path path) throws FolderNotExistsException {
        try {
            return new FolderProxy(service, service.getFolder(mailbox, path));
        } catch (MailboxNotExistsException e) {
            // This shouldn't happen as we should have been given
            // a valid maibox.
            throw new RuntimeException(e);
        }
    }

    public String getUser() {
        return mailbox.getUser();
    }

    public Folder createFolder(Path path) throws FolderExistsException {
        FolderDO folder = service.createFolder(mailbox, path);
        return new FolderProxy(service, folder);
    }

    public void remove(Path path) throws FolderNotExistsException {
        try {
            service.removeFolder(mailbox, path);
        } catch (MailboxNotExistsException e) {
            throw new RuntimeException(e);
        }
    }

    public void renameFolder(Path fromPath, Path toPath) 
            throws FolderExistsException, FolderNotExistsException {
        try {
            service.renameFolder(mailbox, fromPath, toPath);
        } catch (MailboxNotExistsException e) {
            throw new RuntimeException(e);
        }
    }

    public void deliver(Message m) {
        try {
            service.addMessage(mailbox, INBOX, m);
        } catch (FolderNotExistsException e) {
            throw new RuntimeException(e);
        } catch (MailboxNotExistsException e) {
            throw new RuntimeException(e);
        }
    }

    public List<Folder> getFolders(Path basePath) {
        return service.getFolders(mailbox, basePath);
    }

}
